package com.tiger.cloud.controller.crm;

import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.tiger.cloud.auth0.jwt.Token;
import com.tiger.cloud.auth0.jwt.TokenGenerator;
import com.tiger.cloud.auth0.jwt.exceptions.JWTCreationException;
import com.tiger.cloud.auth0.jwt.interfaces.Claim;
import com.tiger.cloud.common.mybatis.BaseController;
import com.tiger.cloud.common.token.PasswordHashUtil;
import com.tiger.cloud.enums.AppSmsType;
import com.tiger.cloud.enums.DeleteEnum;
import com.tiger.cloud.enums.RecommandListAcceptStatus;
import com.tiger.cloud.enums.RecommandListStatus;
import com.tiger.cloud.enums.UserStatusEnum;
import com.tiger.cloud.filter.CurrentUserId;
import com.tiger.cloud.filter.CurrentUserLoginId;
import com.tiger.cloud.filter.CurrentUserWeixin;
import com.tiger.cloud.filter.IgnoreAuth;
import com.tiger.cloud.form.AppSmsMessages;
import com.tiger.cloud.form.CompanyForm;
import com.tiger.cloud.form.ReferTokenForm;
import com.tiger.cloud.form.SysDictSmall;
import com.tiger.cloud.form.UserLoginForm;
import com.tiger.cloud.model.crm.AppSms;
import com.tiger.cloud.model.crm.RecommandList;
import com.tiger.cloud.model.crm.User;
import com.tiger.cloud.model.crm.UserCompanyInfo;
import com.tiger.cloud.model.crm.UserInfo;
import com.tiger.cloud.model.ext.UserAndCompanyInfo;
import com.tiger.cloud.service.crm.IAppSmsService;
import com.tiger.cloud.service.crm.IRecommandListService;
import com.tiger.cloud.service.crm.IUserCompanyInfoService;
import com.tiger.cloud.service.crm.IUserInfoService;
import com.tiger.cloud.service.crm.IUserService;
import com.tiger.cloud.service.system.CommonDict;
import com.tiger.cloud.util.CookieManager;
import com.tiger.cloud.util.DateTimeUtil;
import com.tiger.cloud.util.ErrorCode;
import com.tiger.cloud.util.MagicConstants;
import com.tiger.cloud.util.Response;
import com.tiger.cloud.util.ResponseUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

/**
 * 用户管理
 */
@Controller
@RequestMapping(value = "user")
@Api(value = "用户管理",tags = "用户")
public class UserController extends BaseController {

	@Autowired
	private IUserService userService;
	@Autowired
	private IAppSmsService appSmsService;
	@Autowired
	private IUserInfoService userInfoService;
	@Autowired
	private IUserCompanyInfoService userCompanyInfoService;
	@Autowired
	private IRecommandListService recommandListService ;
	
	/**
	 * 根据二维码获取用户信息
	 */
	@RequestMapping(value = "getByQRCode", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "根据二维码获取用户信息",notes = "根据二维码获取用户信息")
	public Response getByQRCode(@ApiParam(name="id",value="用户id",hidden=true) @CurrentUserId Long userId,
			@ApiParam(name="loginId",value="用户LoginId",hidden=true) @CurrentUserLoginId String mobile,
			@ApiParam(name="weixin",value="用户Weixin",hidden=true) @CurrentUserWeixin String weixin,
			@RequestBody UserLoginForm userLoginForm){
		if(StringUtils.isEmpty(userLoginForm.getQrCode())){
			return ResponseUtil.error(ErrorCode.PARAMETER_INVALID,"qrCode必传");
		}
		User queryUser=new User();
		queryUser.setIsDelete(DeleteEnum.NOMAIL);
		queryUser.setQrCode(userLoginForm.getQrCode());
		User user=userService.findOne(queryUser);
		if(user==null){
			return ResponseUtil.error(ErrorCode.OBJECT_NOT_EXITS,"不存在该用户!");
		}
		UserInfo findUserInfo=new UserInfo();
		findUserInfo.setUserId(user.getId());
		UserInfo userInfo = userInfoService.findOne(findUserInfo);
		if (userInfo == null) {
			return ResponseUtil.error(ErrorCode.OBJECT_NOT_EXITS,"不存在该用户!");
		}
		if(userInfo.getLoginId().equals(mobile)||((!StringUtils.isEmpty(userInfo.getWeiXin()))&&userInfo.getWeiXin().equals(weixin))){
			return ResponseUtil.error(ErrorCode.UN_ADD_USER,"无法添加当前用户为好友!");
		}
		RecommandList findRecommandList=new RecommandList();
		findRecommandList.setIsDelete(DeleteEnum.NOMAIL);
		findRecommandList.setRecommandId(user.getId());
		findRecommandList.setUserId(userId);
		RecommandList recommandList=recommandListService.getRecommand(findRecommandList);
		if(recommandList!=null && (recommandList.getUserId().longValue()==userId.longValue() && recommandList.getIsDelete()==DeleteEnum.NOMAIL)&&recommandList.getStatus()==RecommandListStatus.CREATED){
			return ResponseUtil.errorData(ErrorCode.OBJECT_EXITS,"对象已经存在",user);
		}else if(recommandList!=null && (recommandList.getRecommandId().longValue()==userId.longValue() && recommandList.getAcceptIsDelete()==DeleteEnum.NOMAIL&&recommandList.getAcceptStatus()==RecommandListAcceptStatus.ACCEPTED)){
			return ResponseUtil.errorData(ErrorCode.OBJECT_EXITS,"对象已经存在",user);
		}
		return ResponseUtil.ok(user);
	}
	
	/**
	 * 根据手机号获取用户信息
	 */
	@RequestMapping(value = "getByMobile", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "根据手机号获取用户信息",notes = "根据手机号获取用户信息")
	public Response getByMobile(@ApiParam(name="id",value="用户id",hidden=true) @CurrentUserId Long userId,
			@ApiParam(name="loginId",value="用户LoginId",hidden=true) @CurrentUserLoginId String mobile,
			@ApiParam(name="weixin",value="用户Weixin",hidden=true) @CurrentUserWeixin String weixin,
			@RequestBody UserLoginForm userLoginForm){
		if(StringUtils.isEmpty(userLoginForm.getLoginId())){
			return ResponseUtil.error(ErrorCode.PARAMETER_INVALID,"loginId必传");
		}
		UserInfo userInfo = userInfoService.findUser(userLoginForm.getLoginId());
		if (userInfo == null) {
			return ResponseUtil.error(ErrorCode.OBJECT_NOT_EXITS,"不存在该用户!");
		}
		if(userInfo.getLoginId().equals(mobile)||((!StringUtils.isEmpty(userInfo.getWeiXin()))&&userInfo.getWeiXin().equals(weixin))){
			return ResponseUtil.error(ErrorCode.UN_ADD_USER,"无法添加当前用户为好友!");
		}
		User queryUser=new User();
		queryUser.setIsDelete(DeleteEnum.NOMAIL);
		queryUser.setLoginId(userInfo.getLoginId());
		User userObj=userService.findOne(queryUser);
		if(userObj==null){
			return ResponseUtil.error(ErrorCode.OBJECT_NOT_EXITS,"不存在该用户!");
		}
		RecommandList findRecommandList=new RecommandList();
		findRecommandList.setRecommandId(userObj.getId());
		findRecommandList.setUserId(userId);
		findRecommandList.setIsDelete(DeleteEnum.NOMAIL);
		RecommandList recommandList=recommandListService.getRecommand(findRecommandList);
		if(recommandList!=null && (recommandList.getUserId().longValue()==userId.longValue() && recommandList.getIsDelete()==DeleteEnum.NOMAIL)&&recommandList.getStatus()==RecommandListStatus.CREATED){
			return ResponseUtil.errorData(ErrorCode.OBJECT_EXITS,"对象已经存在",userInfo);
		}else if(recommandList!=null && (recommandList.getRecommandId().longValue()==userId.longValue() && recommandList.getAcceptIsDelete()==DeleteEnum.NOMAIL&&recommandList.getAcceptStatus()==RecommandListAcceptStatus.ACCEPTED)){
			return ResponseUtil.errorData(ErrorCode.OBJECT_EXITS,"对象已经存在",userInfo);
		}
		return ResponseUtil.ok(userInfo);
	}
	
	@RequestMapping(value = "get", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "获取默认用户信息",notes = "获取默认用户信息")
	public Response get(@ApiParam(name="id",value="用户id",hidden=true) @CurrentUserId Long userId){
		UserAndCompanyInfo userAndCompanyInfo= userInfoService.getUserAndCompanyInfo(userId) ;
		return ResponseUtil.ok(userAndCompanyInfo);
	}
	
	@RequestMapping(value = "getUserAndCompanyInfo", method = RequestMethod.POST)
	@ResponseBody
	@IgnoreAuth
	@ApiOperation(value = "获取默认用户信息",notes = "获取默认用户信息")
	public Response getUserAndCompanyInfo(@RequestBody Long userId){
		if(userId==null){
			return ResponseUtil.error(ErrorCode.PARAMETER_INVALID,"userId必传!");
		}
		UserAndCompanyInfo userAndCompanyInfo= userInfoService.getUserAndCompanyInfo(userId) ;
		return ResponseUtil.ok(userAndCompanyInfo);
	}
	
	/**
	 * 获取列表默认值
	 */
	@RequestMapping(value = "getUserInfo", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "获取列表默认值",notes = "获取列表默认值")
	public Response getDefaultFileds(@ApiParam(name="id",value="用户id",hidden=true) @CurrentUserId Long userId,
			@ApiParam(name="id",value="用户手机号",hidden=true) @CurrentUserLoginId String mobile){
		UserInfo userInfo=new UserInfo();
		userInfo.setIsDelete(DeleteEnum.NOMAIL);
		userInfo.setUserId(userId);
		UserInfo findUserInfo=userInfoService.findOne(userInfo);
		findUserInfo.setLoginId(mobile);
		Map<String, List<SysDictSmall>> values = CommonDict.getFileds("user_info");
		Map<String, Object> maps=new HashMap<String, Object>();
		maps.put("userInfo", findUserInfo);
		maps.put("defaults", values);
		return ResponseUtil.ok(maps);
	}
	
	/**
	 * 获取列表默认值
	 */
	@IgnoreAuth
	@RequestMapping(value = "getDefaultFileds", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "获取列表默认值",notes = "获取列表默认值")
	public Response getDefaultFileds(){
		Map<String, List<SysDictSmall>> values = CommonDict.getFileds("user_info");
		return ResponseUtil.ok(values);
	}
	
	/**
	 * 忘记密码
	 */
	@IgnoreAuth
	@RequestMapping(value = "forgotPassword", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "忘记密码",notes = "忘记密码")
	public Response forgotPassword(@ApiParam(name="id",value="用户id",hidden=true) @CurrentUserId Long userId, @RequestBody UserLoginForm userLoginForm) throws NoSuchAlgorithmException, InvalidKeySpecException {
		if (StringUtils.isEmpty(userLoginForm.getLoginId())) {
			return ResponseUtil.error(ErrorCode.PARAMETER_INVALID,"loginId必传");
		}
		//发送验证码
		AppSms appVerifCode=new AppSms();
		appVerifCode.setPhone(userLoginForm.getLoginId());
		appVerifCode.setOrderBy("create_time desc");
		appVerifCode.setCode(userLoginForm.getVerifCode());
		AppSms findAppVerifCode=appSmsService.findOne(appVerifCode);
		if(findAppVerifCode==null){
			return ResponseUtil.error(ErrorCode.INVALID_AUTHENTICATION_CODE,"无效的验证码");
		}
		if(DateTimeUtil.getMillisecondsOfTwoDate(findAppVerifCode.getActiveTime(), DateTimeUtil.getSystemDate())<0){
			return ResponseUtil.error(ErrorCode.VERIFICATION_CODE_EXPIRED,"验证码已过期");
		}
		if (StringUtils.isEmpty(userLoginForm.getPassword())) {
			return ResponseUtil.error(ErrorCode.PARAMETER_INVALID,"password必传");
		}
		User findUser=new User();
		findUser.setLoginId(userLoginForm.getLoginId());
		User user = userService.findOne(findUser);
		if (user == null) {
			return ResponseUtil.error(ErrorCode.OBJECT_NOT_EXITS,"用户已近存在");
		}
		if (user.getStatus() == UserStatusEnum.AUDIT) {
			return ResponseUtil.error("用户处于审核中,暂时无法操作");
		}
		if (user.getStatus() == UserStatusEnum.DISABLE) {
			return ResponseUtil.error("用户处于冻结中,暂时无法操作");
		}
		//更新密码
		User updateUser=new User();
		updateUser.setId(user.getId());
		updateUser.setPassword(PasswordHashUtil.createHash(userLoginForm.getPassword()));
		userService.update(updateUser);
		return ResponseUtil.ok();
	}
	
	/**
	 * 修改密码
	 */
	@IgnoreAuth
	@RequestMapping(value = "updatePassword", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "修改密码",notes = "修改密码")
	public Response updatePassword(@ApiParam(name="id",value="用户id",hidden=true) @CurrentUserId Long userId, @RequestBody UserLoginForm userLoginForm) throws NoSuchAlgorithmException, InvalidKeySpecException {
		if (StringUtils.isEmpty(userLoginForm.getLoginId())) {
			return ResponseUtil.error(ErrorCode.PARAMETER_INVALID,"loginId必传");
		}
		if (StringUtils.isEmpty(userLoginForm.getPassword())) {
			return ResponseUtil.error(ErrorCode.PARAMETER_INVALID,"password必传");
		}
		if (StringUtils.isEmpty(userLoginForm.getOldPassword())) {
			return ResponseUtil.error(ErrorCode.PARAMETER_INVALID,"oldPassword必传");
		}
		User findUser=new User();
		findUser.setLoginId(userLoginForm.getLoginId());
		User user = userService.findOne(findUser);
		if (user == null) {
			return ResponseUtil.error(ErrorCode.OBJECT_NOT_EXITS,"用户不存在");
		}
		if (user.getStatus() == UserStatusEnum.AUDIT) {
			return ResponseUtil.error("用户处于审核中,暂时无法操作");
		}
		if (user.getStatus() == UserStatusEnum.DISABLE) {
			return ResponseUtil.error("用户处于冻结中,暂时无法操作");
		}
		if (!PasswordHashUtil.validatePassword(userLoginForm.getOldPassword(), user.getPassword())) {
            return ResponseUtil.error(ErrorCode.USER_PASSWORD_INVALID,"密码错误");
        }
		//更新密码
		User updateUser=new User();
		updateUser.setId(user.getId());
		updateUser.setPassword(PasswordHashUtil.createHash(userLoginForm.getPassword()));
		if(userService.update(updateUser)>0){
			return ResponseUtil.ok();
		}
		return ResponseUtil.error(ErrorCode.INTERNAL_ERROR,"密码错误,请重新登录");
	}
	
	/**
	 * 处理用户注册
	 */
	@IgnoreAuth
	@RequestMapping(value = "register", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "处理用户注册",notes = "处理用户注册")
	public Response register(  @RequestBody UserLoginForm userLoginForm) throws NoSuchAlgorithmException, InvalidKeySpecException, IllegalArgumentException, JWTCreationException, UnsupportedEncodingException {
		if (StringUtils.isEmpty(userLoginForm.getLoginId())) {
			return ResponseUtil.error(ErrorCode.PARAMETER_INVALID,"参数loginId必传!");
		}
		if (StringUtils.isEmpty(userLoginForm.getPassword())) {
			return ResponseUtil.error(ErrorCode.PARAMETER_INVALID,"参数password必传!");
		}
		if (StringUtils.isEmpty(userLoginForm.getBrowser())) {
			return ResponseUtil.error(ErrorCode.PARAMETER_INVALID,"参数browser必传!");
		}
		if (StringUtils.isEmpty(userLoginForm.getMacUid())) {
			return ResponseUtil.error(ErrorCode.PARAMETER_INVALID,"参数macUid必传!");
		}
		if (StringUtils.isEmpty(userLoginForm.getIp())) {
			return ResponseUtil.error(ErrorCode.PARAMETER_INVALID,"参数ip必传!");
		}
		AppSms appVerifCode=new AppSms();
		appVerifCode.setPhone(userLoginForm.getLoginId());
		appVerifCode.setOrderBy("create_time desc");
		appVerifCode.setCode(userLoginForm.getVerifCode());
		AppSms findAppVerifCode=appSmsService.findOne(appVerifCode);
		if(findAppVerifCode==null){
			return ResponseUtil.error(ErrorCode.INVALID_AUTHENTICATION_CODE,"无效的验证码");
		}
		if(DateTimeUtil.getMillisecondsOfTwoDate(findAppVerifCode.getActiveTime(), DateTimeUtil.getSystemDate())<0){
			return ResponseUtil.error(ErrorCode.VERIFICATION_CODE_EXPIRED,"验证码已过期");
		}
		User findUser=new User();
		findUser.setLoginId(userLoginForm.getLoginId());
		User findUserObj =userService.findOne(findUser);
		if(findUserObj!=null){
			return ResponseUtil.error(ErrorCode.OBJECT_EXITS,"用户已经存在!");
		}
		//注册完成,此用户处于待审核阶段
		User user= userService.register(userLoginForm);
		if (user==null) {
			return ResponseUtil.error(ErrorCode.USER_PASSWORD_INVALID,"密码无效!");
		}
		Map<String, Object> dataMap = new HashMap<String, Object>();
		dataMap.put("userId",user.getId());
		return ResponseUtil.ok(dataMap);
	}
	
	/**
	 * 处理用户注册--->完善用户信息
	 */
	@IgnoreAuth
	@RequestMapping(value = "authCompany", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "完善用户注册信息",notes = "处理用户注册--->完善用户信息")
	public Response authCompany(@ApiParam(name="id",value="用户id",hidden=true) @CurrentUserId Long userId,@RequestBody CompanyForm companyForm) {
		if(StringUtils.isEmpty(companyForm.getBusinessCard())){
			return ResponseUtil.error(ErrorCode.PARAMETER_INVALID,"businessCard必传");
		}
		if(StringUtils.isEmpty(companyForm.getCompanyName())){
			return ResponseUtil.error(ErrorCode.PARAMETER_INVALID,"companyName必传");
		}
		if(userId==null&&companyForm.getUserId()==null){
			return ResponseUtil.error(ErrorCode.PARAMETER_INVALID,"userId必传,注意这里注册时完善用户信息要填入userId,但是在登录后完善企业信息,则不传该值");
		}
		if(companyForm.getUserId()==null){
			companyForm.setUserId(userId);
		}
		UserCompanyInfo userCompanyInfo=userCompanyInfoService.register(companyForm);
		if (userCompanyInfo==null) {
			return ResponseUtil.error(ErrorCode.PARAMETER_INVALID,"注册企业信息无效,请重新选择!");
		}
		return ResponseUtil.ok();
	}
	
	/**
	 * 刷新用户Token
	 */
	@IgnoreAuth
	@RequestMapping(value = "referToken", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "刷新用户Token",notes = "刷新用户Token")
	public Response referToken(@ApiParam(name="id",value="用户id",hidden=true) @CurrentUserId Long userId,@RequestBody ReferTokenForm referTokenForm) throws NoSuchAlgorithmException, InvalidKeySpecException, IllegalArgumentException, JWTCreationException, UnsupportedEncodingException {
		if (StringUtils.isEmpty(referTokenForm.getToken())) {
			return ResponseUtil.error(ErrorCode.PARAMETER_INVALID,"token必传");
		}
		Map<String, Claim> datas = TokenGenerator.getClaims(referTokenForm.getToken());
		Long userId_ = datas.get(MagicConstants.SESSION_USER_ID).asLong();
		String loginId = datas.get(MagicConstants.SESSION_USER_MOBILE).asString();

//		if(userId_!=userId){
//			return ResponseUtil.error(ErrorCode.PARAMETER_INVALID,"只能刷新当前用户token!");
//		}
		User user = new User();
		user.setLoginId(loginId);
		user = userService.findOne(user);
		UserInfo userInfo = new UserInfo();
		userInfo.setUserId(user.getId());
		userInfo = userInfoService.findOne(userInfo);
		Map<String, Object> claims = new HashMap<String, Object>();
		claims.put(MagicConstants.SESSION_USER_ID,userId_);
		claims.put(MagicConstants.SESSION_USER_MOBILE,loginId);
		claims.put(MagicConstants.SESSION_USER_JPUSH_CODE,user.getJpushCode());
		claims.put(MagicConstants.SESSION_USER_WEIXIN,userInfo.getWeiXin());
		Token token=TokenGenerator.create(claims);
		return ResponseUtil.ok(token);
	}
	
	/**
	 * 处理用户登陆
	 */
	@IgnoreAuth
	@RequestMapping(value = "login", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "用户登陆",notes = "处理用户登陆")
	public Response login(HttpServletRequest request,HttpServletResponse response,@RequestBody UserLoginForm userLoginForm) throws NoSuchAlgorithmException, InvalidKeySpecException, IllegalArgumentException, JWTCreationException, UnsupportedEncodingException {
		if (StringUtils.isEmpty(userLoginForm.getLoginId())) {
			return ResponseUtil.error(ErrorCode.PARAMETER_INVALID,"loginId必传!");
		}
		if (StringUtils.isEmpty(userLoginForm.getPassword())) {
			return ResponseUtil.error(ErrorCode.PARAMETER_INVALID,"password必传!");
		}
		User findUser=new User();
		findUser.setLoginId(userLoginForm.getLoginId());
		User user = userService.findOne(findUser);
		if (user == null) {
			return ResponseUtil.error(ErrorCode.OBJECT_NOT_EXITS,"用户不存在");
		}
		try {
			user.setMacUid(userLoginForm.getMacUid());
			user.setRegisterIp(userLoginForm.getIp());
			user.setBrowser(userLoginForm.getBrowser());
			user.setJpushCode(userLoginForm.getJpushCode());
			if(userService.update(user)<=0){
				return ResponseUtil.error("密码错误,请重新登录");
			}
			if (user.getStatus() == UserStatusEnum.UN_DATA) {//0:待审核、1:正常、2:冻结
				return ResponseUtil.errorData(ErrorCode.UN_DATA,user.getId());
			}
			if (user.getStatus() == UserStatusEnum.AUDIT) {//0:待审核、1:正常、2:冻结
				return ResponseUtil.errorData(ErrorCode.AUDIT,user.getId());
			}
			if (user.getStatus() == UserStatusEnum.DISABLE) {//0:待审核、1:正常、2:冻结
				return ResponseUtil.errorData(ErrorCode.DISABLE,user.getId());
			}
			if (user.getStatus() == UserStatusEnum.UN_AUDIT) {//0:待审核、1:正常、2:冻结
				return ResponseUtil.errorData(ErrorCode.UN_AUDIT,user.getId());
			}
			if (user.getStatus() == UserStatusEnum.UN_DATA_AUDIT) {//资料不正确
				return ResponseUtil.errorData(ErrorCode.UN_DATA_AUDIT,user.getId());
			}
			if (!PasswordHashUtil.validatePassword(userLoginForm.getPassword(), user.getPassword())) {
	            return ResponseUtil.errorData(ErrorCode.USER_PASSWORD_INVALID,"密码错误",user.getId());
	        }
		} catch (Exception e) {
			e.printStackTrace();
			return ResponseUtil.errorData(ErrorCode.USER_PASSWORD_INVALID,"密码错误",user.getId());
		}
		try {
			UserInfo findUserInfo=new UserInfo();
			findUserInfo.setUserId(user.getId());
			UserInfo userInfo = userInfoService.findOne(findUserInfo);
			if (userInfo == null) {
				return ResponseUtil.error(ErrorCode.OBJECT_NOT_EXITS,"用户不存在");
			}
			Map<String, Object> claims = new HashMap<String, Object>();
			claims.put(MagicConstants.SESSION_USER_ID, user.getId());
			claims.put(MagicConstants.SESSION_USER_MOBILE,userLoginForm.getLoginId());
			claims.put(MagicConstants.SESSION_USER_JPUSH_CODE,userLoginForm.getJpushCode());
			claims.put(MagicConstants.SESSION_USER_WEIXIN,userInfo.getWeiXin());
			Token token=TokenGenerator.create(claims);
			//留做测试使用
			new CookieManager(request, response).setCookie(MagicConstants.User_Token,token.getToken(), 7*24*60*60*100);
			return ResponseUtil.ok(token);
		} catch (Exception e) {
			e.printStackTrace();
			return ResponseUtil.errorData(ErrorCode.USER_PASSWORD_INVALID,"密码错误",user.getId());
		}
	}

	/**
	 * 处理用户更新
	 */
	@IgnoreAuth
	@RequestMapping(value = "updateUser", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "更新用户",notes = "处理用户更新")
	public Response updateUser(@ApiParam(name="id",value="用户id",hidden=true) @CurrentUserId Long userId,HttpServletRequest request,HttpServletResponse response,@RequestBody UserLoginForm userLoginForm) {
		if (StringUtils.isEmpty(userLoginForm.getJpushCode())) {
			return ResponseUtil.error(ErrorCode.PARAMETER_INVALID,"jpushCode必传!");
		}
		User user = userService.get(userId);
		user.setMacUid(userLoginForm.getMacUid());
		user.setRegisterIp(userLoginForm.getIp());
		user.setBrowser(userLoginForm.getBrowser());
		user.setJpushCode(userLoginForm.getJpushCode());
		if(userService.update(user)<=0){
			return ResponseUtil.error(ErrorCode.UPDATE_DATA_ERROR);
		}
		return ResponseUtil.ok(user.getId());
	}

	
	@RequestMapping(value = "sendRegisterVerifCode", method = RequestMethod.POST)
	@ResponseBody
	@IgnoreAuth
	@ApiOperation(value = "发送注册验证码",notes = "发送注册验证码")
	public Response sendRegisterVerifCode(@RequestBody UserLoginForm userLoginForm) {
		if (userLoginForm==null||StringUtils.isEmpty(userLoginForm.getLoginId())) {
			return ResponseUtil.error(ErrorCode.PARAMETER_INVALID,"loginId必传!");
		}
		User findUser=new User();
		findUser.setLoginId(userLoginForm.getLoginId());
		User user = userService.findOne(findUser);
		if (user != null) {
			return ResponseUtil.error(ErrorCode.OBJECT_EXITS,"用户已经存在");
		}
		String code = RandomStringUtils.randomNumeric(4);
		appSmsService.sendToUID(AppSmsMessages.getMsg(AppSmsMessages.REGISTER_MSG, code), userLoginForm.getLoginId(),  code,AppSmsType.VERIF_CODE, DateTimeUtil.addMinutes(DateTimeUtil.getSystemDate(),5));
		return ResponseUtil.ok();
	}

	
	@RequestMapping(value = "sendVerifCode", method = RequestMethod.POST)
	@ResponseBody
	@IgnoreAuth
	@ApiOperation(value = "发送通用验证码",notes = "发送通用验证码")
	public Response sendVerifCode(@RequestBody UserLoginForm userLoginForm) {
		if(StringUtils.isEmpty(userLoginForm.getPhone())){
			return ResponseUtil.error(ErrorCode.PARAMETER_INVALID,"phone必传!");
		}
		if(!StringUtils.isEmpty(userLoginForm.getLoginId())){
			User findUser = new User();
			findUser.setLoginId(userLoginForm.getLoginId());
			User sysUser = userService.findOne(findUser);
			if (sysUser == null) {
				return ResponseUtil.error(ErrorCode.OBJECT_NOT_EXITS,"用户不存在");
			}
			userLoginForm.setPhone(userLoginForm.getLoginId());
		}
		String code = RandomStringUtils.randomNumeric(4);
		appSmsService.sendToUID(AppSmsMessages.getMsg(AppSmsMessages.REGISTER_MSG, code), userLoginForm.getPhone(), code,AppSmsType.VERIF_CODE, DateTimeUtil.addMinutes(DateTimeUtil.getSystemDate(),5));
		return ResponseUtil.ok();
	}

	
	/**
	 * 更新用户基本信息
	 */
	@RequestMapping(value = "update", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "更新用户基本信息",notes = "更新用户基本信息")
	public Response update(@ApiParam(name="id",value="用户id",hidden=true) @CurrentUserId Long userId,@RequestBody UserInfo userInfo){
		if (userInfo==null||userInfo.getId()==null) {
			return ResponseUtil.error(ErrorCode.PARAMETER_INVALID,"id必传!");
		}
		userInfo.setUserId(userId);
		User updateUser=userService.get(userId);
		if (updateUser==null) {
			return ResponseUtil.error(ErrorCode.OBJECT_NOT_EXITS,"用户不存在");
		}
		UserInfo findUserInfo=new UserInfo();
		findUserInfo.setUserId(userId);
		UserInfo updateUserInfo=userInfoService.findOne(findUserInfo);
		if (updateUserInfo==null) {
			return ResponseUtil.error(ErrorCode.OBJECT_NOT_EXITS,"用户不存在");
		}
		userInfo.setIntegral(updateUserInfo.getIntegral());
		userInfo.setCreateTime(updateUserInfo.getCreateTime());
		userInfo.setId(updateUserInfo.getId());
		boolean success=userService.updateUser(updateUser,userInfo);
		return ResponseUtil.ok(success);
	}
	
//	/**
//	 * 更新用户基本信息
//	 */
//	@RequestMapping(value = "getUserAndCompanyInfo", method = RequestMethod.POST)
//	@ResponseBody
//	@ApiOperation(value = "获取用户基本信息",notes = "获取用户基本信息")
//	public Response getUserAndCompanyInfo(@RequestBody Long userId){
//		if (userId==null||userId==null) {
//			return ResponseUtil.error(ErrorCode.PARAMETER_INVALID,"id必传!");
//		}
//		UserCompanyInfo findUserCompanyInfo=new UserCompanyInfo();
//		findUserCompanyInfo.setUserId(userId);
//		UserCompanyInfo userCompanyInfo=userService.findOne(findUserCompanyInfo);
//		if(userCompanyInfo!=null){
//			userCompanyInfo.setCompanyName(companyForm.getCompanyName());
//			userCompanyInfo.setDistrictId(companyForm.getDistrictId());
//			userCompanyInfo.setProvinceId(companyForm.getProvinceId());
//			userCompanyInfo.setCityId(companyForm.getCityId());
//			userCompanyInfo.setProvinceName(companyForm.getProvinceName());
//			userCompanyInfo.setDistrictName(companyForm.getDistrictName());
//			userCompanyInfo.setCityName(companyForm.getCityName());
//			if(userCompanyInfoDao.update(userCompanyInfo)>0){
//				return userCompanyInfo;
//			}
//		}else{
//			throw new ServiceException(ErrorCode.NOT_FIND_USER_COMPANY);
//		}
//		return ResponseUtil.ok(success);
//	}
	
	
}